#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <string.h>  // 包含 string.h 以使用 strlen

// 日志文件名
#define LOG_FILE "thread_test.log"

// 日志函数
void log_message(const char *message) {
    FILE *log_file = fopen(LOG_FILE, "a");
    if (log_file == NULL) {
        perror("Failed to open log file");
        exit(EXIT_FAILURE);
    }
    time_t now = time(NULL);
    char *time_str = ctime(&now);
    if (time_str != NULL && strlen(time_str) > 0) {
        time_str[strlen(time_str) - 1] = '\0';  // 去掉换行符
    }
    fprintf(log_file, "%s - %s\n", time_str, message);
    fclose(log_file);
}

// 线程函数
void *thread_function(void *arg) {
    const char *message = (const char *)arg;
    for (int i = 0; i < 10; ++i) {
        sleep(1);  // 休眠1秒
        log_message(message);
    }
    pthread_exit(NULL);
}

int main() {
    // 清空或创建日志文件
    FILE *log_file = fopen(LOG_FILE, "w");
    if (log_file == NULL) {
        perror("Failed to create log file");
        exit(EXIT_FAILURE);
    }
    fclose(log_file);

    pthread_t threads[2];
    const char *messages[2] = {"Thread-1 wake up", "Thread-2 wake up"};

    // 创建两个线程
    for (int i = 0; i < 2; ++i) {
        if (pthread_create(&threads[i], NULL, thread_function, (void *)messages[i]) != 0) {
            perror("Failed to create thread");
            exit(EXIT_FAILURE);
        }
    }

    // 等待所有线程完成
    for (int i = 0; i < 2; ++i) {
        if (pthread_join(threads[i], NULL) != 0) {
            perror("Failed to join thread");
            exit(EXIT_FAILURE);
        }
    }

    log_message("All threads completed. Exiting program.");
    printf("运行结束请在thread_test.log日志文件中查看输出");
    return 0;
}
